'use strict'

import { app, protocol, BrowserWindow, ipcMain, Menu } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
// import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'
const windowOpacity = require('./background/windowOpacity.js')
const singleInstanceLock = require('./background/singleInstanceLock.js')
const customProtocol = require('./background/customProtocol.js')
const menu = require('./background/menu.js')
const shortcut = require('./background/shortcut.js')
const sharedObject = require('./background/sharedObject.js') // 初始化共享数据
let mainWindow = null // 主窗口

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

// 注册全局变量
global.sharedObject = sharedObject
// 禁止多开
singleInstanceLock()
// 自定义协议
customProtocol()
// 更新主窗口大小状态
ipcMain.on('updateWindowStatus', (event, arg) => {
  let type = arg.eventType
  let resizable = mainWindow.resizable
  if (mainWindow && !mainWindow.isDestroyed()) {
    if (type === 'minimize') {
      mainWindow.minimize()
    } else if (type === 'fullscreen') {
      if (!resizable) mainWindow.setResizable(true)
      if (process.platform === 'darwin') {
        mainWindow.setSimpleFullScreen(true)
      } else {
        mainWindow.setFullScreen(true)
      }
      if (!resizable) mainWindow.setResizable(false)
    } else if (type === 'restore') {
      if (!resizable) mainWindow.setResizable(true)
      if (process.platform === 'darwin') {
        mainWindow.setSimpleFullScreen(false)
      } else {
        mainWindow.setFullScreen(false)
      }
      if (!resizable) mainWindow.setResizable(false)
    } else if (type === 'close') {
      mainWindow = null
      app.exit(1)
    }
  }
})

async function createWindow() {
  // 设置菜单
  menu(Menu)
  // Create the browser window.
  mainWindow = new BrowserWindow({
    title: '登录',
    width: 1240,
    height: 730,
    show: false,
    center: true,
    frame: false, // 去掉窗口边框
    autoHideMenuBar: true, // 隐藏菜单栏
    titleBarStyle: 'customButtonsOnHover',
    simpleFullscreen: true,
    resizable: process.platform === 'darwin', // 可否调整大小
    movable: true, // 可否移动
    minimizable: true, // 可否最小化
    maximizable: true, // 可否最大化
    fullscreen: false, // MAC下是否可以全屏
    skipTaskbar: false, // 在任务栏中显示窗口
    acceptFirstMouse: true, // 是否允许单击页面来激活窗口
    transparent: process.platform === 'darwin', //允许透明
    closable: true,
    backgroundColor: '#fff',
    allowRunningInsecureContent: true, // 允许一个 https 页面运行 http url 里的资源
    webPreferences: {
      devTools: true, // 是否打开调试模式
      webSecurity: false, // 禁用安全策略
      allowDisplayingInsecureContent: true, // 允许一个使用 https的界面来展示由 http URLs 传过来的资源
      allowRunningInsecureContent: true, // 允许一个 https 页面运行 http url 里的资源
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      // nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION
      nodeIntegration: true
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    mainWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    // await mainWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    // if (!process.env.IS_TEST) mainWindow.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    mainWindow.loadURL('app://./index.html')
  }

  // mainWindow.loadURL('http://bsszjcpc3000.cm-qa.devlb.jsxfedu.net/')

  // 完成第一次绘制后显示
  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
    // 程序界面淡入
    windowOpacity(mainWindow)
  })
  // 监听关闭
  mainWindow.on('close', function (event) {
    // mainWindow.send('close-window-render')
    // event.preventDefault()
  }).on('closed', function () {
    mainWindow = null
  })
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', () => {
  // if (isDevelopment && !process.env.IS_TEST) {
  //   // Install Vue Devtools
  //   try {
  //     await installExtension(VUEJS_DEVTOOLS)
  //   } catch (e) {
  //     console.error('Vue Devtools failed to install:', e.toString())
  //   }
  // }
  // 注册快捷键
  shortcut.regConsole('Command+Control+Alt+F5')
  createWindow()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}
